<script setup lang="ts">
  import { onMounted, ref } from "vue";
  import { useMerchantStore } from "@/stores";

  const merchantStore = useMerchantStore();
  const modalVisible = ref(false);
  const list = ref<any>([]);
  const detail = ref<any>({});

  onMounted(() => {
    fetchList();
  });

  async function fetchList() {
    list.value = await merchantStore.getMerchants();
  }

  function handleAdd() {
    detail.value = {};
    modalVisible.value = true;
  }

  async function handleEdit(record: any) {
    detail.value = await merchantStore.getMerchant({ id: record.id });
    modalVisible.value = true;
  }

  async function handleRemove(record: any) {
    await merchantStore.deleteMerchant({ id: record.id });
    list.value = list.value.filter((item: any) => item.id !== record.id);
  }

  async function handleSave() {
    await merchantStore.saveMerchant({ ...detail.value });
    modalVisible.value = false;
    fetchList();
  }
</script>

<template>
  <div class="page-container">
    <Breadcrumb :items="['用户管理', '角色列表']"></Breadcrumb>
    <a-card :bordered="false">
      <a-button type="primary" size="small" style="margin-bottom: 16px" @click="handleAdd">新增</a-button>
      <a-table :data="list">
        <template #columns>
          <a-table-column title="序号" :width="100">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="商家名称" data-index="name" />
          <a-table-column title="操作" :width="120">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" size="small" @click="handleEdit(record)">编辑</a-button>
                <a-popconfirm content="您确认移除此记录么？" position="tr" @ok="handleRemove(record)">
                  <a-button type="primary" size="small" status="danger">移除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <a-modal :visible="modalVisible" title="商家信息" @cancel="modalVisible = false" @ok="handleSave">
      <a-form :model="{}" auto-label-width>
        <a-form-item label="商家名称" style="margin-bottom: 0">
          <a-input placeholder="请输入商家名称" v-model="detail.name"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
